package cn.edu.pzhu.javaweb.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Application Lifecycle Listener implementation class VisitorListener
 *
 */
@WebListener
public class VisitorListener implements HttpSessionListener {

	private int visitorCount = 0;
    /**
     * Default constructor. 
     */
    public VisitorListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see HttpSessionListener#sessionCreated(HttpSessionEvent)
     */
    public void sessionCreated(HttpSessionEvent se)  { 
         
    	ServletContext application =  se.getSession().getServletContext();
    	//如果没有访问量，写入1，如果有访问量，取出来加1，再写入
    	
    	synchronized (VisitorListener.class) {
    		Object obj = application.getAttribute("VISIT");
        	if (obj==null) {
    			visitorCount = 1;//第一次访问，访问量是1
    		}else {
    			visitorCount = Integer.valueOf(obj.toString())+1;			
    		}
        	System.out.println("有新用户访问了网站,sessionID："+se.getSession().getId());
    		application.setAttribute("VISIT", visitorCount);
		}
    	
         
    }

	/**
     * @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
     */
    public void sessionDestroyed(HttpSessionEvent se)  { 
         // TODO Auto-generated method stub
    }
	
}
